package dao

import (
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
	"log"
)

var db *sql.DB

func init() {
	var err error

	db, err = sql.Open("sqlite3", "./database.db")
	if err != nil {
		log.Fatal(err)
	}

	initTables()
}

// 创建table
func initTables() {
	var err error

	// 创建customer表
	createCustomerTable := `
	CREATE TABLE IF NOT EXISTS customer (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		name TEXT NOT NULL,
		token TEXT NOT NULL,
		created_at DATETIME DEFAULT CURRENT_TIMESTAMP
	);`

	// 创建message表
	createMessageTable := `
	CREATE TABLE IF NOT EXISTS message (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		customer_id TEXT NOT NULL,
		sender TEXT NOT NULL,
		message TEXT NOT NULL,
		timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
	);`

	// 创建feedback表
	createFeedbackTable := `
	CREATE TABLE IF NOT EXISTS feedback (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		customer_id TEXT NOT NULL,
		message TEXT NOT NULL,
		rating INTEGER CHECK(rating BETWEEN 1 AND 5),
	    analysis TEXT NOT NULL,
		timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
	);`

	// 执行建表语句
	for _, table := range []string{createCustomerTable, createMessageTable, createFeedbackTable} {
		_, err = db.Exec(table)
		if err != nil {
			log.Printf("创建表失败: %q", err)
			return
		}

		log.Printf("创建表: %q成功", table)
	}

	log.Printf("database table init success.")
}

func AA() {

}
